/**
 *
 */
package com.engine.Mangers;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.util.EngineUtil;
import com.wfe.db.SessionUtil;
import com.wfe.db.WorkFlowEngineQueryUtil;
import com.wfe.mapping.client.WfProject;
import com.wfe.mapping.client.WfProjectStatus;

/**
 * @author kareem_yehya
 * @06 04 2009 <br>
 *     * @version 1.0.0.1 1 1- change Project status to inprocess
 */

public class ProjectInitiator implements Runnable
{

	public void run()
	{

		while(true)
		{
			try
			{
				System.out.println("Enter ProjectInitiator main Thread");
				List<WfProject> projectList = loadCreatedProjects(100);
				if(projectList != null && projectList.size() > 0)
				{
					for(WfProject project : projectList)
					{
						if(updateProject(project))
						{
							System.out.println(" Start New Project = " + project.getTitle() + " Start Time = " + project.getStartTime());
						}
						// }// if end

					}// for end
				}
				Thread.sleep(500);
			}

			catch(Exception e)
			{
				e.printStackTrace();
			}
		}

	}

	@SuppressWarnings("unchecked")
	private List<WfProject> loadCreatedProjects(int i)
	{
		Session session = null;
		try
		{
			WfProjectStatus createdProjectStatus = getWfProjectStatusByID(1l);
			session = SessionUtil.getSession();
			Criteria criteria = session.createCriteria(WfProject.class);
			criteria.add(Restrictions.eq("wfProjectStatus", createdProjectStatus));
			List<WfProject> retList = criteria.list();

			return retList;
		}catch(Exception e)
		{
			e.printStackTrace();
		}finally
		{
			EngineUtil.closeSession(session);
			System.out.println("Finally");
		}
		return null;
	}

	// @SuppressWarnings("deprecation")
	private boolean updateProject(WfProject project)
	{
		Session session = null;
		try
		{

			WfProjectStatus inprocessProjectStatus = getWfProjectStatusByID(2l);
			project.setStartTime(new Date());
			project.setWfProjectStatus(inprocessProjectStatus);// inprocess
			session = SessionUtil.getSession();
			WorkFlowEngineQueryUtil.updateWfProject(project, session);
			return true;
		}catch(Exception e)
		{

			e.printStackTrace();
			return false;
		}finally
		{
			EngineUtil.closeSession(session);
		}

	}

	private WfProjectStatus getWfProjectStatusByID(long i)
	{

		Session session = null;
		try
		{
			session = SessionUtil.getSession();
			WfProjectStatus status = WorkFlowEngineQueryUtil.getwfProjectStatusByID(i, session);

			return status;
		}catch(Exception e)
		{
			e.printStackTrace();
			return null;
		}finally
		{
			EngineUtil.closeSession(session);
		}

	}

	public static void main(String args[])
	{
		(new Thread(new ProjectInitiator())).start();
	}

}
